package http

import (
	"fmt"
	"github.com/montanaflynn/stats"
	cmap "github.com/orcaman/concurrent-map/v2"
	"hash/fnv"
	"sync"
	"time"
)

var tp99Store sync.Map

type TP99 struct {
	handler   Http
	timeStore cmap.ConcurrentMap[string, []int64]
}

func (client *TP99) Get(url string) {
	fmt.Println("tp99 hit")
	startTime := time.Now()
	client.handler.Get(url)
	duration := time.Since(startTime).Milliseconds()

	client.timeStore.Upsert(url, []int64{duration}, func(exists bool, valueInMap []int64, newValue []int64) []int64 {
		if exists {
			if len(valueInMap) == 100 {
				tp99, _ := stats.Percentile(int64ToFloat64(valueInMap), 99)
				fmt.Println(url, tp99)
				tp99Store.Store(url, int64(tp99))
				return newValue
			}
			fmt.Println(len(valueInMap))
			return append(valueInMap, newValue...)
		}
		return newValue
	})
}

func NewTP99(handler Http) Http {
	tp99 := &TP99{
		handler: handler,
	}

	sharding := func(key string) uint32 {
		h := fnv.New32a()
		h.Write([]byte(key))
		return h.Sum32()
	}

	tp99.timeStore = cmap.NewWithCustomShardingFunction[string, []int64](sharding)
	return tp99
}
